<?php
namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\common\model\GoodsOrderModel;
use app\common\model\MemberModel;
use app\common\service\MsgService;
use web\util\ExpressUtil;
use think\Log;

class Express extends Command {

    protected function configure() {
        $this->setName('express')->setDescription('快递查询');
    }

    protected function execute(Input $input, Output $output) {

        // 一周只能查询,发货通知
        $maxTime = 10;
        $startTime = strtotime(date('2018-09-11'));
        $tempTime = strtotime(date('Y-m-d H:i:s') . '-7 day');
        if ($tempTime > $startTime) {
            $startTime = $tempTime;
        }

        $where = [
            'ispay' => 3,
            'is_delivery' => 0,
            'query_times' => [
                '<=',
                $maxTime
            ], // 最大查询查询次数,
            'ctime' => [
                '>',
                $startTime
            ]
        ];
        $orders = GoodsOrderModel::instance()->where($where)->select();

        $company = '';
        $number = '';
        $this->poll($company, $number);
    }

    private function sendMsg($order) {
        $mid = $order['mid'];
        $member = MemberModel::instance()->find($mid);
        if ($member['openid']) {
            $orderNo = $order['oid'];
            $id = $order['id'];
            $openid = $member['openid'];
            $openid = 'oYj2y0UqPrYvsTkl1KtYmXBYceXI';
            $time = date('Y-m-d H:i', strtotime($order['addtime']));
            $address = $order['receive_addrvalue'] . ' ' . $order['receive_addr'];
            $remark = "商品信息: {$order['goodsname']} x {$order['courier_num']} , 点击查看详情";
            MsgService::sendOrderDeliveryMsg($openid, $id, $orderNo, $time, $address, $remark);
        }
    }

    public function query($orders) {
        foreach ($orders as $order) {
            $expressNo = $order['express_no'];
            $result = ExpressUtil::query($expressNo);
            Log::write("query express_no:$expressNo,result:" . print_r($result, true));
            $status = $result['status'];
            if ($status == "0") {
                // 更新订单信息
                GoodsOrderModel::instance()->where('id', $order['id'])
                    ->inc('query_times', 1)
                    ->update([
                    'is_delivery' => 1
                ]);
                $this->sendMsg($order);
            } else if ($status == '201') {
                GoodsOrderModel::instance()->where('id', $order['id'])
                    ->inc('query_times', 10)
                    ->update();
            } else {
                GoodsOrderModel::instance()->where('id', $order['id'])
                    ->inc('query_times', 1)
                    ->update();
            }
        }
    }

    public function poll($company, $number) {
        $post_data = array();
        $post_data["schema"] = 'json';

        $callbackUrl = get_host() . '/api/v1/express/callback';
        // callbackurl请参考callback.php实现，key经常会变，请与快递100联系获取最新key
        $post_data["param"] = '{"company":"' . $company . '", "number":"' . $number . '","from":"", "to":"",';
        $post_data["param"] = $post_data["param"] . '"key":"buywLfHU8558",';
        $post_data["param"] = $post_data["param"] . '"parameters":{"callbackurl":"' . $callbackUrl . '"}}';

        $url = 'http://www.kuaidi100.com/poll';

        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&"; // 默认UTF-8编码格式
        }

        $post_data = substr($o, 0, - 1);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $result = curl_exec($ch); // 返回提交结果，格式与指定的格式一致（result=true代表成功）

        var_dump($result);
    }

    private function get($expressName) {
        $map = [
            'EMS' => 'youzhengguonei',
            'EMS经济' => 'youzhengguonei',
            '圆通' => 'yuantong',
            '天天电子' => 'tiantian',
            '德邦' => 'debangwuliu',
            '德邦快递' => 'debangwuliu',
            '德邦物流' => 'debangwuliu',
            '申通' => 'shentong',
            '申通快递' => 'shentong',
            '百世快运' => 'baishiwuliu',
            '百世快递电子' => 'baishiwuliu',
            '百世电子' => 'baishiwuliu',
            '邮政' => 'youzhengguonei',
            '顺丰' => 'shunfeng',
            '顺丰快递' => 'shunfeng',
            '顺丰速运' => 'shunfeng'
        ];
        if(key_exists($expressName, $map)){
            return $map[$expressName];
        }
        return '';
    }
}